package cn.chenwx.bbsforum.controller;

import cn.chenwx.bbsforum.entity.User;
import cn.chenwx.bbsforum.service.UserService;
import cn.chenwx.bbsforum.utils.BlogJSONResult;
import cn.chenwx.bbsforum.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller

public class RegisterController {

    @GetMapping("/user/register")
    public String register(){

        return "register";
    }

    @Autowired
    private UserService userService;


    @PostMapping("/register")
    @ResponseBody
    public BlogJSONResult userRegister(User user, @RequestParam("username") String username, @RequestParam("phone") String phone, @RequestParam("password") String password){

        User user1=userService.findUserByName(username);
        if (user1==null){
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            user.setUsername(username);
            user.setPassword(bCryptPasswordEncoder.encode(password));
            user.setPhone(phone);
            userService.addUser(user);
            return BlogJSONResult.ok();
        }else {
            return BlogJSONResult.build(55, "该用户已存在", null);
        }

    }

    /**
     * 用户检测
     * @param username 用户名称
     * @return 不存在 -- ok()     存在 -- errorMsg("该用户已存在")
     */
    @PostMapping("/user/usernameCheck")
    @ResponseBody
    public BlogJSONResult usernameCheck(String username){
        if(StringUtil.BLANK.equals(username)){
            return BlogJSONResult.build(4,"用户名为空",null);
        }
        else if(userService.usernameIsExist(username)){
            return BlogJSONResult.errorMsg("该用户已存在");
        }else {
            return  BlogJSONResult.ok();
        }
    }



}
